import { defineConfig } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { dirResolver, DirResolverHelper } from 'vite-auto-import-resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import path from 'path'
// 导入fs模块
import fs from 'fs'
import modifyAssemble from './src/scripts/modify-assemble'

// 项目路径中不能包含空格和中文字符
// 中文正则
const reg = /[\u4e00-\u9fa5]/
if (__dirname.includes(' ') || reg.test(__dirname)) {
    // 终止程序
    throw new Error(`项目路径:
        ${__dirname}
        中不能包含 [空格] 和 [中文]
        请修改后重试`)
}

const pathSrc = path.resolve(__dirname, 'src')
export default defineConfig(({ mode }: any) => {
    console.log('当前环境:', mode)
    return {
        base: '/mobile/',
        server: {
            hmr: true,
            port: 9999,
            host: true,
            // https: {
            //     cert: fs.readFileSync(path.join(__dirname, '/cert.crt')),
            //     key: fs.readFileSync(path.join(__dirname, '/cert.key')),
            // },
            proxy: {
                '^/proxy': {
                    target: 'http://192.168.1.129:9999/', // 后台服务器的源
                    changeOrigin: true, // 修改源
                    rewrite: (path) => path.replace(/^\/proxy/, ''),
                },
            },
        },
        resolve: {
            alias: {
                '@': path.resolve(__dirname, 'src'),
                '@pluginPackage': path.resolve(__dirname, 'src/pages/pluginPackage'),
            },
        },
        plugins: [
            uni(),
            modifyAssemble(mode)(),
            vueJsx(),
            DirResolverHelper(),
            AutoImport({
                include: [/\.[tj]sx?$/, /\.ts$/, /\.vue$/],
                resolvers: [
                    dirResolver({
                        target: 'src/composables',
                        include: ['useConvert', 'useSafeHeight'],
                    }),
                ],
                dts: path.resolve(pathSrc, '../types/auto-imports.d.ts'),
                eslintrc: {
                    enabled: true,
                    filepath: './types/.eslintrc-auto-import.json',
                    globalsPropValue: true,
                },
            }),
        ],
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: `@import "./src/assets/css/global.scss";`,
                },
            },
        },
        build: {
            minify: 'terser',
            terserOptions: {
                compress: {
                    drop_console: mode === 'production',
                    drop_debugger: mode === 'production',
                },
            },
        },
    }
})
